package com.javasm.mingming.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author javasm
 * @version 0.1
 * @className CorsConfig
 * @descriptioin:
 * @date 2024/12/31 15:08
 * @since jdk11
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter(){
        //预先的配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //所有的请求,都要过滤,都添加跨域
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }
    private CorsConfiguration buildConfig(){
        CorsConfiguration config = new CorsConfiguration();
        //配置 允许所有的作用域
        config.addAllowedOrigin("*");
        //头信息
        config.addAllowedHeader("*");
        //方法
        config.addAllowedMethod("*");
        //cookie,session会失效
        config.setAllowCredentials(true);
        //有效期
        config.setMaxAge(3600L);

        return config;
    }
}
